package cn.ymjr.sys.config.weixin;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 微信接口
 *
 * @author wx
 */
public class WeiXinApiUtil {



    //获取基础token请求Url
    public static String getTokenUrl()throws IOException {
        return String.format(WeiXinConfig.getAccessToken(), WeiXinConfig.getAppId(), WeiXinConfig.getAppSecert());
    }

    //获取JsApi使用权限
    public static String getJsApiTicketUrl(String token)throws IOException {
        return String.format(WeiXinConfig.getJsApiTicket(), token);
    }

    //网页授权OAuth2.0根据code获取token
    public static String getOAuthTokenUrl(String code)throws IOException {
        return String.format(WeiXinConfig.getGetOauthToken(), WeiXinConfig.getAppId(), WeiXinConfig.getAppSecert(), code);
    }

    //网页授权OAuth2.0获取用户信息
    public static String getOAuthUserinfoUrl(String token, String openid)throws IOException {
        return String.format(WeiXinConfig.getGetOauthUserInfo(), token, openid);
    }
    //获取模板消息
    public static String getSendMessage(String token){
        return String.format(WeiXinConfig.getSendMessage(),token);
    }
    public static String urlEnodeUTF8(String str) {
        String result = str;
        try {
            result = URLEncoder.encode(str, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 签名算法,生成JS-SDK权限验证的签名
     *
     * @param jsapi_ticket
     * @param url
     * @return
     */
    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";
        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + nonce_str +
                "&timestamp=" + timestamp +
                "&url=" + url;
        //System.out.println(string1);
        try {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //ret.put("url", url);
        //ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }

}
